package org.biogroovy.io.eutils

import groovy.json.JsonSlurper;
import groovy.util.slurpersupport.NodeChild;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.List;
import java.util.Map;

import org.biogroovy.io.AbsJsonReader
import org.biogroovy.io.AbsXmlSlurper
import org.biogroovy.io.IFetcher;
import org.biogroovy.models.Drug
import org.w3c.dom.Node;



/**
 * This class is responsible for fetching drug information from PubChem's PUG
 * REST service.
 * 
 * @link https://pubchem.ncbi.nlm.nih.gov/pug_rest/PUG_REST.html
 */
class PubChemJsonReader extends AbsJsonReader<Drug>{

	 private static final String[] properties = [
		'XLogP',
		'CanonicalSmiles',
		'MolecularFormula',
		'MolecularWeight',
		'InChIKey',
		'IUPACName',
		'RotatableBondCount'
		]


	@Override
	public Drug fetch(String id) throws IOException {
		 
		Drug drug = new Drug();
		
		URL url = getUrl(id, null);
		
		JsonSlurper slurper = new JsonSlurper();
		Map jsonPropMap = (Map)slurper.parse(url.openStream());

		println jsonPropMap.PropertyTable.Properties[0]
		
		parse(drug, jsonPropMap.PropertyTable.Properties[0])
		drug.pubchemId = id;
		return drug;
	}

	@Override
	public URL getUrl(String pubchemId, Map<String, String> paramMap) {
		String urlStr = "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/${pubchemId}/property/${properties.join(',')}/JSON"
		return new URL(urlStr);
	}

	@Override
	public List<Drug> fetchAll(String id) throws IOException {
		
		List<Drug> drugList = new ArrayList<>();
		
		
		return drugList;
	}

	@Override
	public void parse(Drug drug, Map jsonPropMap) {
		drug.molFormula = jsonPropMap.MolecularFormula;
		drug.molWeight = jsonPropMap.MolecularWeight;
		drug.smiles = jsonPropMap.CanonicalSMILES;
		drug.inChiKey = jsonPropMap.InChIKey;
		drug.xLogp = jsonPropMap.XLogP;
		drug.rotatableBonds = jsonPropMap.RotatableBondCount;
		drug.name = jsonPropMap.IUPACName;
		drug.pubchemId = jsonPropMap.CID;
	}	


	@Override
	public Drug read(InputStream inputStream) throws IOException {
		
		Drug drug = new Drug();
		JsonSlurper slurper = new JsonSlurper();
		Map<String, String> jsonPropMap = (Map)slurper.parse(inputStream);

		parse(drug, jsonPropMap.PropertyTable.Properties)
		
		return drug;
	}

	@Override
	public List<Drug> readList(InputStream inputStream) throws IOException {
		
		return null;
	}

	@Override
	public IFetcher<Drug> getNewInstance() {
		return new PubChemJsonReader();
	}
	
	

}
